package com.ffapp.f9164.td.bugly;

import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.BleLog;
import com.clj.fastble.utils.HexUtil;
import com.ffapp.f9164.td.R;
import com.ffapp.f9164.td.basis.Constants;
import com.ffapp.f9164.td.eventbus.PopHandleMessage;
import com.ffapp.f9164.td.home.HomeBaseActivity;
import com.ffapp.f9164.td.util.CountDown;
import com.ffapp.f9164.td.util.OwnerConfirmDialog;

import java.io.UnsupportedEncodingException;

import butterknife.BindView;
import butterknife.OnClick;
import my.BleUtils;
import my.CheckUtils;
import my.FileUtils;
import my.TimeUtils;

public class DebugIndexActivity extends HomeBaseActivity {

    @BindView(R.id.tv_result)
    TextView tvResult;
    @BindView(R.id.et_order)
    EditText etOrder;
    @BindView(R.id.btn_send)
    Button btnSend;

    private static StringBuffer atShowResult = new StringBuffer();
    ;

    private boolean isFinish = false;

    private CountDown mCountDownTimer;
    private CountDown showMessageOnTextView;
    private static final long MAX_TIME = 25 * 1000;

    private boolean bleNotifyIsOpen = false;

    private Handler submitHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 75://75提交
                    if (!isFinish) {
                        showToast("无响应，请重试");
                        dismissProgress();
                        mCountDownTimer.cancel();
                    }
                    break;
                case 83:
                    refreshLogView(HexUtil.hexStringToString(atShowResult.toString()));
                    break;
            }
        }
    };


    @Override
    public void initViews() {
        super.initViews();
        //让布局向上移来显示软键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_debug_index);
        setTitle("调试信息");
        tvResult.setMovementMethod(ScrollingMovementMethod.getInstance());
        initCountDownTimer();

        View decorView = getWindow().getDecorView();
        View contentView = findViewById(Window.ID_ANDROID_CONTENT);
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(getGlobalLayoutListener(decorView, contentView));
    }

    //让edit悬浮在软键盘上面
    private ViewTreeObserver.OnGlobalLayoutListener getGlobalLayoutListener(final View decorView, final View contentView) {
        return new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                decorView.getWindowVisibleDisplayFrame(r);

                int height = decorView.getContext().getResources().getDisplayMetrics().heightPixels;
                int diff = height - r.bottom;

                if (diff != 0) {
                    if (contentView.getPaddingBottom() != diff) {
                        contentView.setPadding(0, 0, 0, diff);
                    }
                } else {
                    if (contentView.getPaddingBottom() != 0) {
                        contentView.setPadding(0, 0, 0, 0);
                    }
                }
            }
        };
    }

    public void initCountDownTimer() {

        showMessageOnTextView = new CountDown();
        showMessageOnTextView.setMillisInFuture(200);
        showMessageOnTextView.setCountdownInterval(100);
        showMessageOnTextView.setCountDownListener(new CountDown.CountDownListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onFinish() {
                submitHandler.sendEmptyMessage(83);
            }

            @Override
            public void onTick(long millisUntilFinished) {
//                mTimerTv.setText(TimeTools.getCountTimeByLong(millisUntilFinished));
            }
        });


        mCountDownTimer = new CountDown();
        mCountDownTimer.setMillisInFuture(MAX_TIME);
        mCountDownTimer.setCountdownInterval(1000);
        mCountDownTimer.setCountDownListener(new CountDown.CountDownListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onFinish() {
                submitHandler.sendEmptyMessage(75);
            }

            @Override
            public void onTick(long millisUntilFinished) {
//                mTimerTv.setText(TimeTools.getCountTimeByLong(millisUntilFinished));
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
    }


    @OnClick(R.id.btn_send)
    public void sendAtOrder() {

        openNotify();

        isFinish = false;
        final String keyWord = etOrder.getText().toString().trim();
        if (TextUtils.isEmpty(keyWord)) {
            showToast("命令不可为空");
            return;
        }
        showLoading();
        mCountDownTimer.start();
        try {
            String a = HexUtil.chineseWordToGbk(keyWord) + "0D0A";
            BleUtils.write(a, new BleWriteCallback() {
                @Override
                public void onWriteSuccess(final int current, final int total, final byte[] justWrite) {

                    if (current == total) {
                        BleLog.d("下发设置发送成功");

                    }
                }

                @Override
                public void onWriteFailure(final BleException exception) {
                    BleLog.d("下发设置发送失败");
                }
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }


    @OnClick(R.id.btn_save_debug)
    public void saveDebug() {

        OwnerConfirmDialog dialog = new OwnerConfirmDialog(mContext, new OwnerConfirmDialog.OnNamePostListener() {
            @Override
            public void onNamePost(String name) {
                try {
                    String time = TimeUtils.getTimeLongToStrByFormat(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss");
                    String fileName = Constants.DIR_DEBUG + name + ".txt";
                    FileUtils.cacheString("" + fileName, "" + tvResult.getText().toString().trim());
                    showToast("保存成功");
                } catch (Exception e) {
                    showToast("保存失败");
                }
            }
        }, "文件名称");
        dialog.show();

    }

    @OnClick(R.id.btn_clear_debug)
    public void clearDebug() {
        tvResult.setText("");
    }

    @Override
    protected void onResume() {
        super.onResume();
        new Handler().postDelayed(new Runnable() {
            public void run() {
                openNotify();
            }
        }, 2000);

    }


    private void openNotify() {
        if (!bleNotifyIsOpen) {
            BleUtils.notify(new BleNotifyCallback() {
                @Override
                public void onNotifySuccess() {
                    bleNotifyIsOpen = true;
                    BleLog.d("通知监听成功");
                }

                @Override
                public void onNotifyFailure(BleException exception) {
                    bleNotifyIsOpen = false;
                    BleLog.d("通知监听失败");
                }

                @Override
                public void onCharacteristicChanged(byte[] data) {
                    for (Byte a : data) {
                        atShowResult.append("" + String.format("%02X", a));
                    }
                    isFinish = true;
                    mCountDownTimer.cancel();
                    showMessageOnTextView.start();
//                    refreshLogView(HexUtil.hexStringToString(atShowResult.toString()));
                    dismissProgress();
                }

                @Override
                public void onError() {
                    isFinish = true;
                    mCountDownTimer.cancel();
                    dismissProgress();
                    tvResult.append("ERROR");
                }
            });
        }
    }

    private boolean isFront = false;

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("DebugIndexActivity ===", "onPause");
        BleUtils.write(HexUtil.strToHex("AT+BTDEBUG=0"));
        bleNotifyIsOpen = false;
        BleUtils.stopNotify();
        isFront = false;
    }


    void refreshLogView(String msg) {
        try {
            tvResult.append("" + msg);
            atShowResult.setLength(0);
        } catch (OutOfMemoryError e) {
            atShowResult.setLength(0);
            tvResult.setText("");
            throw e;
        }
//        int offset = tvResult.getLineCount() * tvResult.getLineHeight();
//        if (offset > tvResult.getHeight()) {
//            tvResult.scrollTo(0, offset - tvResult.getHeight());
//        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        submitHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onMessageEvent(PopHandleMessage event) {
        super.onMessageEvent(event);
        if (isFront) {
            BleUtils.reConnect(mContext, new BleUtils.BleUtilLoginCallBack() {
                @Override
                public void isLogin(boolean isSuccess, String message) {
                    showToast("" + message);
                    dismissProgress();
                }
            });
        }
    }
}
